package com.zhijian.medical.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.zhijian.medical.dao.local.PcrYbzbMapper;
import com.zhijian.medical.entity.dto.PcrYbzbProjectDto;
import com.zhijian.medical.entity.po.ExperimentProcessSample;
import com.zhijian.medical.entity.po.ExperimentProcessSampleLog;
import com.zhijian.medical.entity.po.Pcr;
import com.zhijian.medical.entity.po.PcrYbzb;
import com.zhijian.medical.entity.vo.request.ExperimentProcessSampleSearchVo;
import com.zhijian.medical.entity.vo.request.PcrYbzbSaveOrUpdateVo;
import com.zhijian.medical.entity.vo.request.PcrYbzbSearchVo;
import com.zhijian.medical.entity.vo.response.ExperimentProcessSampleVo;
import com.zhijian.medical.entity.vo.response.PcrYbzbVo;
import com.zhijian.medical.enums.AllExperimentationStepStatusEnum;
import com.zhijian.medical.enums.ExperimentTypeEnum;
import com.zhijian.medical.enums.PcrKnbStatusEnum;
import com.zhijian.medical.enums.StatusEnum;
import com.zhijian.medical.holder.CurrentUserHolder;
import com.zhijian.medical.service.ExperimentProcessSampleLogService;
import com.zhijian.medical.service.ExperimentProcessSampleService;
import com.zhijian.medical.service.PcrService;
import com.zhijian.medical.service.PcrYbzbService;
import com.zhijian.medical.util.AssertUtil;
import com.zhijian.medical.util.JsonUtil;
import com.zhijian.medical.util.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 荧光PCR-样本准备区业务处理层
 *
 * @author HCG
 * @version: 1.0
 * @date 2022-08-30 18:00:33
 */
@Slf4j
@Service
public class PcrYbzbServiceImpl implements PcrYbzbService {

    @Autowired
    private PcrYbzbMapper mapper;

    @Autowired
    private PcrService pcrService;

    @Autowired
    private ExperimentProcessSampleService experimentProcessSampleService;

    @Autowired
    private ExperimentProcessSampleLogService experimentProcessSampleLogService;

    @Override
    public PcrYbzb selectById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public PcrYbzb selectByPcrId(Long pcrId) {
        return mapper.selectByPcrId(pcrId);
    }

    @Override
    public PcrYbzbVo selectVoById(Long id) {
        return mapper.selectVoById(id);
    }

    @Override
    public PcrYbzbVo selectVoByPcrId(Long pcrId) {
        PcrYbzbVo pcrYbzbVo = mapper.selectVoByPcrId(pcrId);
        if (Objects.isNull(pcrYbzbVo)) {
            return null;
        }
        Pcr pcr = pcrService.selectById(pcrId);
        if (Objects.isNull(pcr)) {
            return null;
        }
        pcrYbzbVo.setResult(pcr.getStatus() > PcrKnbStatusEnum.YBZBQ.getCode().byteValue() ?
                AllExperimentationStepStatusEnum.END.getCode().byteValue() : AllExperimentationStepStatusEnum.UN_END.getCode().byteValue());
        pcrYbzbVo.setResultStr(pcr.getStatus() > PcrKnbStatusEnum.YBZBQ.getCode().byteValue() ?
                AllExperimentationStepStatusEnum.END.getDesc() : AllExperimentationStepStatusEnum.UN_END.getDesc());
        String projectData = pcrYbzbVo.getProjectData();
        if (StringUtils.isNotBlank(projectData)) {
            pcrYbzbVo.setProjectDataList(JsonUtil.toArray(projectData, PcrYbzbProjectDto.class));
        }
        return pcrYbzbVo;
    }

    @Override
    public void deleteById(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public void deleteByPcrId(Long pcrId) {
        mapper.deleteByPcrId(pcrId);
    }

    @Override
    public Long insert(PcrYbzb pcrYbzb) {
        Date now = new Date();
        pcrYbzb.setCreateTime(now);
        pcrYbzb.setUpdateTime(now);
        if (Objects.isNull(pcrYbzb.getYblkqpcztmqj())) {
            pcrYbzb.setYblkqpcztmqj(StatusEnum.UN_NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(pcrYbzb.getYblkqpmlqpqqjqpj())) {
            pcrYbzb.setYblkqpmlqpqqjqpj(StatusEnum.UN_NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(pcrYbzb.getYblkqpczywyc())) {
            pcrYbzb.setYblkqpczywyc(StatusEnum.UN_NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(pcrYbzb.getTlshhrsslqptlhsh())) {
            pcrYbzb.setTlshhrsslqptlhsh(StatusEnum.UN_NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(pcrYbzb.getTlshhrsslqphers())) {
            pcrYbzb.setTlshhrsslqphers(StatusEnum.UN_NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(pcrYbzb.getTlshhrsgczywyc())) {
            pcrYbzb.setTlshhrsgczywyc(StatusEnum.UN_NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(pcrYbzb.getLdt())) {
            pcrYbzb.setLdt(StatusEnum.NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(pcrYbzb.getQpj())) {
            pcrYbzb.setQpj(StatusEnum.NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(pcrYbzb.getPhy())) {
            pcrYbzb.setPhy(StatusEnum.NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(pcrYbzb.getRsj())) {
            pcrYbzb.setRsj(StatusEnum.NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(pcrYbzb.getSyhqjhwhslqpj())) {
            pcrYbzb.setSyhqjhwhslqpj(StatusEnum.UN_NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(pcrYbzb.getSyhclsyfqw())) {
            pcrYbzb.setSyhclsyfqw(StatusEnum.UN_NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(pcrYbzb.getSyhjxsyqzwxzs())) {
            pcrYbzb.setSyhjxsyqzwxzs(StatusEnum.UN_NORMAL.getCode().byteValue());
        }
        return mapper.insert(pcrYbzb) > 0 ? pcrYbzb.getId() : 0L;
    }

    @Override
    public boolean update(PcrYbzb pcrYbzb) {
        Date now = new Date();
        pcrYbzb.setUpdateTime(now);
        return mapper.updateByPrimaryKey(pcrYbzb) != 0;
    }

    @Override
    public Integer count(PcrYbzbSearchVo pcrYbzbSearchVo) {
        return mapper.count(pcrYbzbSearchVo);
    }

    @Override
    public List<PcrYbzbVo> selectList(PcrYbzbSearchVo pcrYbzbSearchVo) {
        return mapper.selectList(pcrYbzbSearchVo);
    }

    @Override
    public Page<PcrYbzbVo> selectPage(PcrYbzbSearchVo pcrYbzbSearchVo) {
        //先直接查总数
        int count = count(pcrYbzbSearchVo);
        //分页
        Page<PcrYbzbVo> page = new Page<>(true, count, pcrYbzbSearchVo.getPageNum(), pcrYbzbSearchVo.getPageSize());
        pcrYbzbSearchVo.setStartIndex(page.getStartIndex());
        page.setPage(true);
        page.setTotalCount(count);
        List<PcrYbzbVo> responseVos = this.selectList(pcrYbzbSearchVo);
        page.setData(responseVos);
        return page;
    }

    @Transactional(rollbackFor = Exception.class, value = "localTransactionManager")
    @Override
    public boolean saveOrUpdate(PcrYbzbSaveOrUpdateVo pcrYbzbSaveOrUpdateVo) {
        Long pcrId = pcrYbzbSaveOrUpdateVo.getPcrId();
        Pcr pcr = pcrService.selectById(pcrId);
        AssertUtil.notNull(pcr, "此实验不存在或者已被删除");
        if (pcr.getStatus() < PcrKnbStatusEnum.HSZBQ.getCode().byteValue()) {
            //将实验的状态修改
            pcrService.updateByPrimaryKeySelective(Pcr.builder()
                    .id(pcrId)
                    .status(PcrKnbStatusEnum.HSZBQ.getCode().byteValue())
                    .build());
        }
        List<PcrYbzbProjectDto> projectDataList = pcrYbzbSaveOrUpdateVo.getProjectDataList();
        if (CollectionUtil.isNotEmpty(projectDataList)) {
            pcrYbzbSaveOrUpdateVo.setProjectData(JsonUtil.toString(projectDataList));
            //把肿瘤细胞比例修改掉
            projectDataList.forEach(p -> experimentProcessSampleService.updateByPrimaryKeySelective(ExperimentProcessSample.builder()
                    .id(p.getId())
                    .zlxbbl(p.getZlxbbl())
                    .build()));
        }
        PcrYbzb dbParam = new PcrYbzb();
        BeanUtils.copyProperties(pcrYbzbSaveOrUpdateVo, dbParam);
        PcrYbzb oldPcrYbzb = this.selectByPcrId(pcrId);
        if (Objects.isNull(oldPcrYbzb)) {
            dbParam.setJcrq(DateUtil.formatDate(new Date()));
            this.insert(dbParam);
        } else {
            dbParam.setId(oldPcrYbzb.getId());
            dbParam.setJcrq(oldPcrYbzb.getJcrq());
            this.update(dbParam);
        }
        List<ExperimentProcessSampleVo> experimentProcessSampleVos = experimentProcessSampleService.selectList(ExperimentProcessSampleSearchVo.builder()
                .mainType(ExperimentTypeEnum.PCR.getCode().byteValue())
                .experimentProcessId(pcrId)
                .build());
        //保存样本日志
        experimentProcessSampleLogService.saveBatch(experimentProcessSampleVos.stream().map(e -> ExperimentProcessSampleLog.builder()
                .sampleId(e.getId())
                .fishId(pcrId)
                .mainType(ExperimentTypeEnum.PCR.getCode().byteValue())
                .op(String.format("%s%s-%s", pcr.getName(), pcr.getProcessNumber(), PcrKnbStatusEnum.YBZBQ.getDesc()))
                .opUser(CurrentUserHolder.getUser().getName())
                .build()).collect(Collectors.toList()));
        return true;
    }

}